package com.ls.lserp.modules.trade.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Maps;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.service.CrudService;
import com.ls.lserp.common.utils.CacheUtils;
import com.ls.lserp.common.utils.CollectionsUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.SpringContextHolder;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.modules.order.dao.AuditInfoDao;
import com.ls.lserp.modules.order.entity.AuditInfo;
import com.ls.lserp.modules.order.entity.OrderMateriel;
import com.ls.lserp.modules.sys.dao.DictDao;
import com.ls.lserp.modules.sys.dao.UserDao;
import com.ls.lserp.modules.sys.entity.Dict;
import com.ls.lserp.modules.sys.entity.User;
import com.ls.lserp.modules.sys.utils.UserUtils;
import com.ls.lserp.modules.trade.dao.HandBookDao;
import com.ls.lserp.modules.trade.entity.HandBook;


/**
 * @ClassName: HandBookService
 * @Description: 采购手册
 * 
 * @author 
 * @date 2017年3月10日 下午18:40:40
 *
 */

@Service
@Transactional(readOnly = true)
public class HandBookService extends CrudService<HandBookDao, HandBook>{
	
    @Autowired
    private HandBookDao handBookDao;
    
    @Autowired
    private UserDao userDao;
    
    // 审核表
    @Autowired
    private AuditInfoDao  auditInfoDao;
    
	private static DictDao dictDao = SpringContextHolder.getBean(DictDao.class);

	public static final String CACHE_DICT_MAP = "dictMap";

	public static final String CACHE_DICT_VALUE_MAP = "dictValueMap";
	
	public static final String HAND_BOOK_NO = "HANDBOOK";
    
    /**
      * @Title: findList
      * @Description: 查询
      * @param @param page
      * @param @param handBook
      * @param @return
      * @return Page<HandBook> 
      * @throws
      */
    public Page<HandBook> findList(Page<HandBook> page, HandBook handBook) {
    	
		// tab页分，检索条件设定(0:全部,1:待审核,2:审核通过,3:审核拒绝)
		int tabFlg = handBook.getTabPageStatus();
		handBook.setHandbookDelFlg(HandBook.DEL_FLAG_NORMAL);
		if(1==tabFlg){
			handBook.setHandbookAuditStatus(ResourcesUtil.getConfig("reserver_meterial_wait_accept"));
		}else if(2==tabFlg){
			handBook.setHandbookAuditStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
		}else if(3==tabFlg){
			handBook.setHandbookAuditStatus(ResourcesUtil.getConfig("reserver_meterial_no"));
		}else if(4==tabFlg){
			handBook.setHandbookDelFlg(HandBook.DEL_FLAG_DELETE);
			handBook.setHandbookAuditStatus("");
		}else if(5==tabFlg){
			handBook.setHandbookAuditStatus(ResourcesUtil.getConfig("audit_uncommit"));
		}else{
			handBook.setHandbookAuditStatus("");
		}
		
        // 设置分页参数
    	handBook.setPage(page);
    	
    	handBook.setAuditPhaseCd(ResourcesUtil.getConfig("audit_phase_handbook"));
		List<HandBook> resultList = handBookDao.findList(handBook);
		
		for(HandBook hb : resultList){
			hb.setAuditUserName(getUserAllName(hb.getAuditUserId()));
		}
		
        // 执行分页查询
        page.setList(resultList);
        
        return page;
    }
    
	/**
	 * 根据ID获取用户
	 * @param id
	 * @return 取不到返回null
	 */
	public String getUserAllName(long id){
		if(id==0){
			return "";
		}
		User user = (User)CacheUtils.get(UserUtils.USER_CACHE, UserUtils.USER_CACHE_ID_ + id);
		if (user ==  null){
			user = userDao.get(id);
			if (user == null){
				return "";
			}
		}
		return user.getFirstName()+user.getLastName();
	}
	
	/**
	 * @Title: 合同订单选择一览
	 * @Description: 一览查询
	 * @param page
	 * @param orderMateriel
	 * @return Page<OrderMateriel>
	 */
	public Page<OrderMateriel> findIndentList(Page<OrderMateriel> page, OrderMateriel orderMateriel) {
		
		// 设置分页参数
		orderMateriel.setPage(page);
		
		// 执行分页查询
		page.setList(handBookDao.findIndentList(orderMateriel));
		return page;
	}
	
	/**
	 * @Title: 出口明细信息
	 * @Description: 查询
	 * @param indentId
	 * @return HandBook
	 */
	public HandBook getExportDetailsByIndentId(Long indentId) {
		
		HandBook resultHandBook = handBookDao.getExportDetailsByIndentId(indentId);
		
		if(resultHandBook!=null){
			if(StringUtils.isNotEmpty(resultHandBook.getHandbookCurrencyCd())){
			   resultHandBook.setHandbookCurrency(getDictEnShortName(resultHandBook.getHandbookCurrencyCd()));
			}
			
			// 总价格(数量*单价)
			resultHandBook.setHandbookAmount((checkBigDecimalNull(resultHandBook.getHandbookQuantity()).multiply(checkBigDecimalNull(resultHandBook.getHandbookPrice()))).setScale(2, BigDecimal.ROUND_HALF_UP));
		}
		
		return resultHandBook;
	}
	
	/**
	 * 返回数据字典名称
	 * 
	 * @param value
	 * @return
	 */
	public static String getDictEnShortName(String value) {

		Map<String, Dict> dictValueMap = (Map<String, Dict>) CacheUtils.get(CACHE_DICT_VALUE_MAP);

		if (dictValueMap == null) {

			dictValueMap = Maps.newHashMap();
			for (Dict dict : dictDao.findAllList(new Dict())) {
				dictValueMap.put(dict.getItemCode() + "-" + dict.getItemValue(), dict);
			}
		}

		Dict returnDict = dictValueMap.get(value);

		if (returnDict != null) {
			return returnDict.getItemShortNameEn();
		} else {
			return "";
		}
	}
	
    /**
     * @Title: findMaterialList
     * @Description: 查询物料
     * @param @param handBook
     * @param @return
     * @return List<HandBook>
     * @throws
     */
   
   public List<HandBook> findMaterialList(HandBook handBook) {
       
       return handBookDao.findMaterialList(handBook);
   }
    
   /**
    * @Title: findIxportDetails
    * @Description: 选择进口料件
    * @param @param handBook
    * @param @return
    * @return List<HandBook>
    * @throws
    */
  
  public List<HandBook> findIxportDetails(String commaMaterialReservePurchaseId) {
	  HandBook pHandBook = new HandBook();
	  pHandBook.setCommaMaterialReservePurchaseId(commaMaterialReservePurchaseId);
	  
		List<HandBook> resultHandBookList = handBookDao.findIxportDetails(pHandBook);
		
		if(!CollectionsUtils.isEmpty(resultHandBookList)){
			for(HandBook hb : resultHandBookList){
				
				// 货币单位
				if(StringUtils.isNotEmpty(hb.getHandbookCurrencyCd())){
					hb.setHandbookCurrency(getDictEnShortName(hb.getHandbookCurrencyCd()));
				}
				
				// 总价格(数量*单价)
				hb.setHandbookAmount((checkBigDecimalNull(hb.getHandbookQuantity()).multiply(checkBigDecimalNull(hb.getHandbookPrice()))).setScale(2, BigDecimal.ROUND_HALF_UP));
			}
		}
	  return resultHandBookList;
  }
  
	/**
	 * check BigDecimal
	 * @param cost
	 * @return 取不到返回0
	 */
	public BigDecimal checkBigDecimalNull(BigDecimal cost){
		if(cost==null){
			return new BigDecimal("0");
		}
		return cost;
	}
	
	/**
	 * @Title: exportTotal
	 * @Description: 出口总数量和总值计算
	 * @param @param handBook
	 * @param @param model
	 * @param @param session
	 * @param @return
	 * @return String 
	 * @throws
	 */
	public HandBook exportTotal(List<HandBook> exportList){
		HandBook hb = new HandBook();
		if(CollectionsUtils.isEmpty(exportList)){
			hb.setHandbookExportNumber(new BigDecimal("0"));
			hb.setHandbookExportSum(new BigDecimal("0"));
			return hb;
		}
		
		BigDecimal totalNumber = new BigDecimal("0");
		BigDecimal totalSum = new BigDecimal("0");
		for(HandBook forHb : exportList){
			totalNumber = totalNumber.add(checkBigDecimalNull(forHb.getHandbookQuantity()));
			totalSum = totalSum.add(checkBigDecimalNull(forHb.getHandbookAmount()));
		}
		hb.setHandbookExportNumber(totalNumber);
		hb.setHandbookExportSum(totalSum);
		return hb;
	}
	
	/**
	 * @Title: importTotal
	 * @Description: 进口总数量和总值计算
	 * @param @param handBook
	 * @param @param model
	 * @param @param session
	 * @param @return
	 * @return String 
	 * @throws
	 */
	public HandBook importTotal(List<HandBook> importList){
		HandBook hb = new HandBook();
		if(CollectionsUtils.isEmpty(importList)){
			hb.setHandbookImportNumber(new BigDecimal("0"));
			hb.setHandbookImportSum(new BigDecimal("0"));
			return hb;
		}
		
		BigDecimal totalNumber = new BigDecimal("0");
		BigDecimal totalSum = new BigDecimal("0");
		for(HandBook forHb : importList){
			totalNumber = totalNumber.add(checkBigDecimalNull(forHb.getHandbookQuantity()));
			totalSum = totalSum.add(checkBigDecimalNull(forHb.getHandbookAmount()));
		}
		hb.setHandbookImportNumber(totalNumber);
		hb.setHandbookImportSum(totalSum);
		return hb;
	}
	
	/**
	  * @Title: saveDict
	  * @Description: 保存基准数据
	  * @param @param dict
	  * @return void 
	  * @throws
	  */
	@Transactional(readOnly = false)
	public void saveHandBook(HandBook handBook) {
		
		// 判断新建编辑
		//若为null 执行插入语句（新建）
		if (handBook.getId()==null){			
			handBook.preInsert();
			handBook.setVersion(1L);
			
			// 取得手册编号
	        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");  
	        String dateNowStr = sdf.format(new Date());  
			handBook.setHandbookNo(HAND_BOOK_NO+dateNowStr);
			
			if(StringUtils.isEmpty(handBook.getHandbookStatus())){
			// 设置手册状态
			handBook.setHandbookStatus(ResourcesUtil.getConfig("handbook_status_begin"));
			}
			
			if(StringUtils.isEmpty(handBook.getHandbookAuditStatus())){
			// 手册审核状态
			handBook.setHandbookAuditStatus(ResourcesUtil.getConfig("audit_uncommit"));
			}
			
			handBookDao.insertHandbookP(handBook);
			
		// 编辑
		}else{
			// 更新数据
			handBook.preUpdate();
			handBookDao.update(handBook);
			// 删除出口成本数据
			handBookDao.deleteHandbookSytle(handBook);
			// 删除进口物料数据
			handBookDao.deleteHandbookMaterials(handBook);
		}
		
		// 判断list是否为空
		if(!CollectionsUtils.isEmpty(handBook.getExportDetailsList())){
			// 遍历赋值
	        for(HandBook  hb : handBook.getExportDetailsList()){
        		//创建人信息
        	    hb.preInsert();
        	    hb.setVersion(1L);
        	    hb.setId(handBook.getId());
        	    // 执行子项插入语句
        	    handBookDao.insertHandbookSytleS(hb);
			}
		}
		
		// 判断list是否为空
		if(!CollectionsUtils.isEmpty(handBook.getImportDetailsList())){
			// 遍历赋值
	        for(HandBook  hb : handBook.getImportDetailsList()){
        		//创建人信息
        	    hb.preInsert();
        	    hb.setVersion(1L);
        	    hb.setId(handBook.getId());
        	    // 执行子项插入语句
        	    handBookDao.inserthandbookMaterialsS(hb);
			}
		}
	}
	
	   /**
	    * 查询出口成品
	    * @param handBook
	    * @return
	    */
	   
	   public HandBook findExportDetailsByHandBookId(HandBook handBook) {
		   HandBook hb = new HandBook();
		   List<HandBook> resultFindExportDetails = handBookDao.findExportDetailsByHandBookId(handBook);
		   List<String> commaIndentIdList = null;
		   
		   if(!CollectionsUtils.isEmpty(resultFindExportDetails)){
			   
			   hb.setExportDetailsList(resultFindExportDetails);
			   
			   // 设定货币略称
			   commaIndentIdList = new ArrayList<String>();
			   for(HandBook forHb : hb.getExportDetailsList()){
				   // 货币单位
				   if(StringUtils.isNotEmpty(forHb.getHandbookCurrencyCd())){
					   forHb.setHandbookCurrency(getDictEnShortName(forHb.getHandbookCurrencyCd()));
				   }
				   
				   if(forHb.getIndentId()!=null){
					   if(!commaIndentIdList.contains(forHb.getIndentId().toString())){
					      commaIndentIdList.add(forHb.getIndentId().toString());
					   }
				   }
			   }
		   }
		   

		   HandBook resultExportTotal = exportTotal(hb.getExportDetailsList());
		   hb.setHandbookExportNumber(resultExportTotal.getHandbookExportNumber());
		   hb.setHandbookExportSum(resultExportTotal.getHandbookExportSum());
		   
		   if(!CollectionsUtils.isEmpty(commaIndentIdList)){
			   hb.setCommaIndentId(CollectionsUtils.convertToString(commaIndentIdList, ",")); 
		   }
		   
	       // 执行查询
	       return hb;
	   }
	   
	   /**
	    * 查询出口成品
	    * @param handBook
	    * @return
	    */
	   
	   public HandBook findImportDetailsByHandBookId(HandBook handBook) {
		   HandBook hb = new HandBook();
		   List<HandBook> resultFindImportDetails = handBookDao.findImportDetailsByHandBookId(handBook);
		   
		   if(!CollectionsUtils.isEmpty(resultFindImportDetails)){
			   hb.setImportDetailsList(resultFindImportDetails);
	     		// 设定货币略称
			   for(HandBook forHb : hb.getImportDetailsList()){
					if(StringUtils.isNotEmpty(forHb.getHandbookCurrencyCd())){
						forHb.setHandbookCurrency(getDictEnShortName(forHb.getHandbookCurrencyCd()));
					}
			   }
		   }
		   
		   HandBook resultImportTotal = importTotal(hb.getImportDetailsList());
		   hb.setHandbookImportNumber(resultImportTotal.getHandbookImportNumber());
		   hb.setHandbookImportSum(resultImportTotal.getHandbookImportSum());
	       // 执行查询
	       return hb;
	   }
	   
		/**
		  * @Title: deleteDict
		  * @Description: 删除基准数据(逻辑删除)
		  * @param @param dict
		  * @return void 
		  * @throws
		  */
		
		@Transactional(readOnly = false)
		public void deleteHandBook(HandBook handBook) {
			// 执行逻辑删除
			handBookDao.delete(handBook);
		}
		
		/**
		 * @Title: resetSum
		 * @Description: 求总值
		 * @param @param handBook
		 * @param @param model
		 * @param @param session
		 * @param @return
		 * @return String 
		 * @throws
		 */
		public BigDecimal resetSum(BigDecimal num,BigDecimal price){
			// 数量*单价
			return (checkBigDecimalNull(num).multiply(checkBigDecimalNull(price))).setScale(2, BigDecimal.ROUND_HALF_UP);
		}
		
	    /**
	     * @Title: findAuditList
	     * @Description: 查询所有履历
	     * @param @param auditInfo
	     * @param @return
	     * @return List<AuditInfo> 
	     * @throws
	     */
	   public AuditInfo findAuditInfo(AuditInfo auditInfo) {
		   AuditInfo audit = new AuditInfo();
		   audit.setAuditList(auditInfoDao.findAllList(auditInfo));
		   audit.setAuditStatus(auditInfoDao.findAuditAcceptCount(auditInfo));
	       // 执行查询
	       return audit;
	   }
	   
	   /**
	    * @Title: getAuditResult
	    * @Description: 审核结果
	    * @param @param auditInfo
	    * @param @return
	    * @return 审核结果通过数
	    * @throws
	    */
	  
	  public long getAuditResult(AuditInfo auditInfo) {
		   
	      return auditInfoDao.findAuditAcceptCount(auditInfo);
	  }
	  
		/**
		  * @Title: saveAudit
		  * @Description: 保存履历信息
		  * @param @param auditInfo
		  * @return void 
		  * @throws
		  */
		@Transactional(readOnly = false)
		public void saveAuditInfo(AuditInfo auditInfo) {
			
			 // 插入履历表
		     auditInfo.preInsert();
		     auditInfo.setAuditDate(new Date());
		     auditInfo.setAuditUserId(UserUtils.getUser().getId());
	         // 新建版本号赋值1
		     auditInfo.setVersion(1L);
		     auditInfoDao.insert(auditInfo);
		     
		     // 修正核料生产状态
		     auditInfo.preUpdate();
		     handBookDao.updateHandbookPStatus(auditInfo);
		}
}
